package com.colabo.j2ee.web.oaf.security.impl;

import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.colabo.j2ee.web.core.common.CommonConstants;
import com.colabo.j2ee.web.core.exception.ServiceException;
import com.colabo.j2ee.web.core.pkgenerator.IPKGenerator;
import com.colabo.j2ee.web.core.service.impl.DefaultServiceImpl;
import com.colabo.j2ee.web.core.vo.SessionUserHolder;
import com.colabo.j2ee.web.oaf.orgnization.IUnitService;
import com.colabo.j2ee.web.oaf.orgnization.model.SCUserProfileVO;
import com.colabo.j2ee.web.oaf.orgnization.model.SCUnitProfileVO;
import com.colabo.j2ee.web.oaf.security.IDataPermissionService;
import com.colabo.j2ee.web.oaf.security.PermissionConstant;
import com.colabo.j2ee.web.oaf.security.model.IPDataPermissionVO;
import com.colabo.j2ee.web.oaf.security.model.IPUnitPermissionVO;

public class DataPermissionServiceImpl extends DefaultServiceImpl implements
		IDataPermissionService {
	Log log = LogFactory.getLog(DataPermissionServiceImpl.class);
	
	private IPKGenerator keyService = null;
	private IUnitService unitService = null;

	public List findSelfDataPermission(String position) throws ServiceException {
		Map para = new HashMap();
		para.put("position", position);
		return find_iBatis("permission.findSelfDataPermission", para);
	}

	public List findSelfDataPermission(String position, String object)
			throws ServiceException {
		Map para = new HashMap();
		para.put("object", object);
		para.put("position", position);
		return find_iBatis("permission.findSelfDataPermission", para);
	}

	public List findUnitDataPermission(String position) throws ServiceException {
		Map para = new HashMap();
		para.put("position", position);
		return find_iBatis("permission.findUnitDataPermission", para);
	}

	public boolean hasUnitDataPermission(String position, String unit)
			throws ServiceException {
		Map para = new HashMap();
		para.put("position", position);
		para.put("unit", unit);

		List list = find_iBatis("permission.findUnitDataPermission", para);

		boolean rv = false;
		if (list != null && list.size() > 0) {
			rv = true;
		}
		return rv;
	}

	public List listAllSelfDataPermission() throws ServiceException {
		return find_iBatis("permission.findAllSelfDataPermission",
				new HashMap());
	}

	public void setKeyService(IPKGenerator keyService) {
		this.keyService = keyService;
	}

	public void savePositionSelfDataPermission(Map sdPermission,
			String position) throws ServiceException {
		
		List deleteBeanList = (ArrayList) sdPermission.get(CommonConstants.DELETE_BEAN_LIST);
		List insertBeanList = (ArrayList) sdPermission.get(CommonConstants.INSERT_BEAN_LIST);
		
		int deletecount = deleteBeanList.size();
		int insertcount = insertBeanList.size();

		/*String sql = "DELETE FROM IP_PERMISSION_ASS WHERE PA_TYPE='SD' AND PA_POSITION='"
				+ position + "'";
		getJdbcTemplate().execute(sql);*/

		IPDataPermissionVO dp = null;

		for (int i = 0; i < insertcount; i++) {
			dp = (IPDataPermissionVO) insertBeanList.get(i);
			
			if(checkPermissionExistByCode("SD", position, dp.getId())){
				continue;
			}
			
			insertPermission("SD",position, dp.getId());	
		}
		
		for (int i = 0; i < deletecount; i++) {
			dp = (IPDataPermissionVO) deleteBeanList.get(i);
			deletePermission("SD",position, dp.getId());
		}
	}

	public void savePositionUnitDataPermission(Map upPermission,
			String position) throws ServiceException {
		
		List deleteBeanList = (ArrayList) upPermission.get(CommonConstants.DELETE_BEAN_LIST);
		List insertBeanList = (ArrayList) upPermission.get(CommonConstants.INSERT_BEAN_LIST);
		
		int deletecount = deleteBeanList.size();
		int insertcount = insertBeanList.size();

		//String sql = "DELETE FROM IP_PERMISSION_ASS WHERE PA_TYPE='UP' AND PA_POSITION='"
		//		+ position + "'";
		//getJdbcTemplate().execute(sql);

		IPUnitPermissionVO dp = null;

		for (int i = 0; i < insertcount; i++) {
			dp = (IPUnitPermissionVO) insertBeanList.get(i);
			
			//查找刚岗位是否已经存在该数据权限，如果已存在，则跳过，否则增加该权限。
			if(checkPermissionExistByCode("UP", position, dp.getId())){
				continue;
			}
			insertPermission("UP",position, dp.getId());			
		}
		
		for (int i = 0; i < deletecount; i++) {
			dp = (IPUnitPermissionVO) deleteBeanList.get(i);
			/*String sql = "DELETE FROM IP_PERMISSION_ASS WHERE PA_TYPE='UP' AND PA_POSITION='"
					+ position + "' AND PA_DP='"+dp.getId()+"'";*/
			deletePermission("UP",position, dp.getId());
			//getJdbcTemplate().execute(sql);
		}

	}
	
	private void insertPermission(String type, String position, String id)
	throws ServiceException {
		StringBuffer sql = new StringBuffer();
		String key;
		key = keyService.getUUIDKey();

		sql.append("INSERT INTO IP_PERMISSION_ASS ");
		sql.append("(PA_TYPE, PA_DP, PA_POSITION, PA_ID) VALUES (?, ?, ?, ?)");

		Object[] params = new Object[] { type, id, position, key };
		int[] types = new int[] { Types.CHAR, Types.CHAR, Types.VARCHAR, Types.CHAR };
		getJdbcTemplate().update(sql.toString(), params, types);
	}

	private void deletePermission(String type, String position, String id)
			throws ServiceException {
		StringBuffer sql = new StringBuffer();

		sql.append("DELETE FROM IP_PERMISSION_ASS WHERE 1=1 ");
		sql.append(" and PA_TYPE =? AND PA_POSITION=? AND PA_DP=?");

		Object[] params = new Object[] { type, position, id };
		int[] types = new int[] { Types.CHAR, Types.VARCHAR, Types.CHAR };
		getJdbcTemplate().update(sql.toString(), params, types);
	}
	
	private boolean checkPermissionExistByCode(String type, String position,
			String id) throws ServiceException {
		String sql = "SELECT PA_ID FROM IP_PERMISSION_ASS WHERE PA_TYPE=? AND PA_POSITION=? AND PA_DP=?";
		Object[] obj = new Object[3];
		obj[0] = type;
		obj[1] = position;
		obj[2] = id;
		List list = getJdbcTemplate().queryForList(sql, obj);
		if(list!=null && list.size()>0){
			return true;
		}
		return false;
	}

	public List findUnitDataPermission(String position, String direction,
			String offset) throws ServiceException {
		Map para = new HashMap();
		para.put("position", position);
		return find_iBatis("permission.findUnitDataPermissionUnitCode", para);
	}

	public boolean hasUnitDataPermission(String position, List unit)
			throws ServiceException {
		return false;
	}

	public String findSelfDataPermissionStringList(String position,
			String object) throws ServiceException {
		Map para = new HashMap();
		para.put("object", object);
		para.put("position", position);

		List list = find_iBatis("permission.findSelfDataPermissionStringList",
				para);

		if (null == list) {
			return "";
		}

		return list2String(list, null);
	}

	public IUnitService getUnitService() {
		return unitService;
	}

	public void setUnitService(IUnitService unitService) {
		this.unitService = unitService;
	}

	public IPKGenerator getKeyService() {
		return keyService;
	}

	public List findSelfDataPermission(List position) throws ServiceException {
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		return find_iBatis("permission.findSelfDataPermission4List", para);
	}

	public List findSelfDataPermission(String position, String dpCode,
			String object) throws ServiceException {
		Map para = new HashMap();
		para.put("position", position);
		para.put("code", dpCode);
		para.put("object", object);
		return find_iBatis("permission.findSelfDataPermission", para);
	}

	public List findSelfDataPermissionByPermissionCode(String position,
			String dpCode) throws ServiceException {
		Map para = new HashMap();
		para.put("position", position);
		para.put("code", dpCode);
		return find_iBatis("permission.findSelfDataPermission", para);
	}

	public List findSelfDataPermissionByPermissionCode(List position,
			List dpCode) throws ServiceException {
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		para.put("code", list2String(dpCode, "'"));
		return find_iBatis("permission.findSelfDataPermission4List", para);
	}

	public List findSelfDataPermissionByUser(String user, String dpCode)
			throws ServiceException {
		List list = find_iBatis("permission.findPositionByStaffId", user);

		if (list == null || list.size() < 1) {
			list = new ArrayList();
		}

		list.add(CommonConstants.PUBLIC_PEMISSION_POSITION_ID);

		Map para = new HashMap();
		para.put("position", list2String(list, "'"));
		if(null!=dpCode&&dpCode.length()>0){			
			para.put("code", "'" + dpCode + "'");
		}
		return find_iBatis("permission.findSelfDataPermission4List", para);
	}

	public String findSelfDataPermissionStringList(List position, List dpCode,
			String object) throws ServiceException {
		Map para = new HashMap();
		if (object != null && object.length() > 0) {
			para.put("object", object);
		}
		if (position != null && position.size() > 0) {
			para.put("position", list2String(position, "'"));
		}
		if (dpCode != null && dpCode.size() > 0) {
			para.put("code", list2String(dpCode, "'"));
		}
		List list = find_iBatis(
				"permission.findSelfDataPermissionStringList4List", para);

		if (null == list) {
			return "";
		}

		return list2String(list, null);
	}

	public List findUnitDataPermission(List position) throws ServiceException {
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		return find_iBatis("permission.findUnitDataPermission4List", para);
	}

	public List findUnitDataPermission(String position, String upCode)
			throws ServiceException {
		Map para = new HashMap();
		para.put("position", position);
		para.put("code", upCode);
		if(null!=upCode&&upCode.length()>0){			
			para.put("code", "'"+upCode+"'");
		}
		return find_iBatis("permission.findUnitDataPermission", para);
	}

	public List findUnitDataPermission(List position, List upCode)
			throws ServiceException {
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		if(null!=upCode&&upCode.size()>0){			
			para.put("code", list2String(upCode, "'"));
		}
		
		return find_iBatis("permission.findUnitDataPermission4List", para);
	}

	public List findUnitDataPermission(String user, List upCode)
			throws ServiceException {
		List list = find_iBatis("permission.findPositionByStaffId", user);

		if (list == null || list.size() < 1) {
			list = new ArrayList();
		}

		list.add(CommonConstants.PUBLIC_PEMISSION_POSITION_ID);

		Map para = new HashMap();
		para.put("position", list2String(list, "'"));
		para.put("code", list2String(upCode, "'"));
		return find_iBatis("permission.findUnitDataPermission4List", para);
	}

	public List findUnit(String user, String upCode, String direction)
			throws ServiceException {
		List list = find_iBatis("permission.findPositionByStaffId", user);

		if (list == null || list.size() < 1) {
			list = new ArrayList();
		}

		list.add(CommonConstants.PUBLIC_PEMISSION_POSITION_ID);
		
		List org1Auth=new ArrayList();
		List org2Auth=new ArrayList();
		List orgAllAuth=new ArrayList();

		SCUnitProfileVO org1Relust=null;
		SCUnitProfileVO org2Relust=null;
		
		List resultList=new  ArrayList();
		Map orgPara = new HashMap();
		orgPara.put("position", list2String(list, "'"));
		orgPara.put("code", "'SYSTEM_DEFAULT_ALL'");
		orgAllAuth=find_iBatis("permission.findUnitDataPermission4List", orgPara);
		
		//如果定义的全部组织策略，则查找全部组织，并退出
		if(orgAllAuth!=null && orgAllAuth.size()>0){
			//定义了ORGA策略
			resultList = unitService.getUnitsBySuperUnit(null);
			return resultList;
		}
		
		//查找是否定义的一级组织策略
		orgPara.put("code", "'SYSTEM_DEFAULT_LEVEL1'");
		org1Auth=find_iBatis("permission.findUnitDataPermission4List", orgPara);
		if(org1Auth!=null && org1Auth.size()>0){
			List staffList=(List)find_iBatis("org.getStaffByStaffid", user);
			if(staffList==null ||staffList.size()==0 ){	
			}else{
				SCUserProfileVO staff= (SCUserProfileVO)staffList.get(0);
				SCUnitProfileVO unitVO=staff.getUnit();
				String id = unitVO.getLogicalKey();
				org1Relust= getUnit4OrgGroup(id,"1");
			}
		}	
		
		orgPara.put("code", "'SYSTEM_DEFAULT_LEVEL2'");
		org2Auth=find_iBatis("permission.findUnitDataPermission4List", orgPara);		
		if(org2Auth!=null && org2Auth.size()>0){
			List staffList=(List)find_iBatis("org.getStaffByStaffid", user);
			if(staffList==null ||staffList.size()==0 ){	
			}else{
				SCUserProfileVO staff= (SCUserProfileVO)staffList.get(0);
				SCUnitProfileVO unitVO=staff.getUnit();
				String id = unitVO.getLogicalKey();
				org2Relust= getUnit4OrgGroup(id,"2");
			}
		}
		List findResult = findUnit(list, upCode, direction, "100");
        if(findResult ==null){
        	findResult=new ArrayList();
        }

        if(org1Relust != null ){
        	findResult.add(org1Relust);
        }
        if(org2Relust != null ){
        	findResult.add(org2Relust);
        }
        List result=getNodDupList(findResult);
        List a=filterResult(result);
		return a;
	}
	
	private List filterResult(List raw){
		// 参数判断
		//Assert.isNull(raw, "Parameter - List is null");
		//Assert.notEmpty(raw, "Parameter - List contains no elements");
//		List rawcapy=new ArrayList();
//		Collections.copy(rawcapy, raw);
		if(raw == null || raw.size()==0){
			return new ArrayList();
		}
		// 转为局部变量操作
		List tmp =raw;
		Collections.sort(tmp);
		// 如果实现了Object的HashCode方法和equals方法
		// 也可用set来做除去重复项操作
		// 这里采用map的key为唯一的特点除去重复项
		// 算法复杂度为nlogn
		Map container = new HashMap();
		for (int i = 0; i < tmp.size(); i++) {
			SCUnitProfileVO ori = (SCUnitProfileVO) tmp.get(i);
			String oriPath = ori.getTreePath();
			container.put(ori.getLogicalKey(), ori);
			for (int j = i+1; j < tmp.size(); j++) {
				SCUnitProfileVO tar= (SCUnitProfileVO) tmp.get(j);
				String tarPath = tar.getTreePath();
				if (tarPath.indexOf(oriPath) < 0) {
					container.put(tar.getLogicalKey(), tar);
				}
				if(tar.getSupervisionUnit()!=null){				
					if (!isExist(tar.getSupervisionUnit(),raw)){
						container.put(tar.getLogicalKey(), tar);
					}
				}
			}
			// 循环后，
			// 容器大小为循环次数则表明后续元素已被过滤一次则不用继续执行
			// 或者
			// 容器大小达到元素个数说明所有元素均无包含关系则不用继续执行
			if (container.size() == i+1 || container.size() == tmp.size()){
				break;
			}
		}
		
		return new ArrayList(container.values());
	}
	
	private List filterResult(List raw,List authOrgList){
		// 参数判断
		//Assert.isNull(raw, "Parameter - List is null");
		//Assert.notEmpty(raw, "Parameter - List contains no elements");
//		List rawcapy=new ArrayList();
//		Collections.copy(rawcapy, raw);
		if(raw == null || raw.size()==0){
			return new ArrayList();
		}
		// 转为局部变量操作
		List tmp =raw;
		Collections.sort(tmp);
		// 如果实现了Object的HashCode方法和equals方法
		// 也可用set来做除去重复项操作
		// 这里采用map的key为唯一的特点除去重复项
		// 算法复杂度为nlogn
		Map container = new HashMap();
		for (int i = 0; i < tmp.size(); i++) {
			SCUnitProfileVO ori = (SCUnitProfileVO) tmp.get(i);
			String oriPath = ori.getTreePath();
			container.put(ori.getLogicalKey(), ori);
			for (int j = i+1; j < tmp.size(); j++) {
				SCUnitProfileVO tar= (SCUnitProfileVO) tmp.get(j);
				String tarPath = tar.getTreePath();
				if(tar.getSupervisionUnit()!=null){				
					if (!isExist(tar.getSupervisionUnit(),authOrgList)){
						container.put(tar.getLogicalKey(), tar);
					}
				}
				else if (tarPath.indexOf(oriPath) < 0) {
					container.put(tar.getLogicalKey(), tar);
				}
			}
			// 循环后，
			// 容器大小为循环次数则表明后续元素已被过滤一次则不用继续执行
			// 或者
			// 容器大小达到元素个数说明所有元素均无包含关系则不用继续执行
			if (container.size() == i+1 || container.size() == tmp.size()){
				break;
			}
		}
		
		return new ArrayList(container.values());
	}
	
	public boolean isExist(SCUnitProfileVO superunit,List l){	
		HashMap  resultMap = new HashMap();
		for(int i=0;i<l.size();i++){
			   HashMap unitMap = (HashMap)l.get(i);
			   String id= (String)unitMap.get("id");
			   String tree= (String)unitMap.get("tree");
			   String direction= (String)unitMap.get("direction");
			   try {
				if(isTheUnitHasPriv(resultMap, id,
							tree, direction, superunit)){
					   return true;	
				   }
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}/*
	  	for (int i = 0; i < l.size(); i++) {					
	  		SCUnitProfileVO temp = (SCUnitProfileVO) l.get(i);
	  		if(unitid.trim().equals(temp.getUnitid().trim())){
				return true;							  
			}			
		}	*/		
	   return false;
	}
	
	public List getNodDupList(List sourceList){
		HashMap hashMap=new HashMap();
		if(sourceList !=null && sourceList.size()>0){
		   List list =new ArrayList();
	       Iterator sourceIter = sourceList.iterator();
			while(sourceIter.hasNext()){
				SCUnitProfileVO u1=(SCUnitProfileVO) sourceIter.next();
			    if(u1 !=null){
				    hashMap.put(u1.getLogicalKey(), u1);
				}
			}
			
			Iterator sourceNameIter= hashMap.keySet().iterator();
			while(sourceNameIter.hasNext()){
				String u1Name=(String) sourceNameIter.next();
				SCUnitProfileVO _u1= (SCUnitProfileVO)hashMap.get(u1Name);
				list.add(_u1);
			}
			return list;
		}
		
		return sourceList;
	}
	
	public SCUnitProfileVO getUnit4OrgGroup(String unitid,String type) throws ServiceException{
		List unitList=new ArrayList();
		new ArrayList();
		if(unitid == null || unitid.trim().length()==0){
			return null;
		}
		unitList=(List)find_iBatis("org.getUnitByUnitid", unitid);
		if(unitList == null || unitList.size()==0){
			return null;
		}
		SCUnitProfileVO unitVO =(SCUnitProfileVO)unitList.get(0);
		String level= unitVO.getUnitLevel();	
		if(level !=null && level.equals(type)){		
			return unitVO;
		}
		
		SCUnitProfileVO superUnitVO=unitVO.getSupervisionUnit();
		if(superUnitVO ==null ){
			return null;
		}
        String superUnitId=superUnitVO.getLogicalKey();
		return getUnit4OrgGroup(superUnitId,type);
			
	}
	public List testAuth() throws ServiceException {
		List a= new ArrayList();
		a.add("83D01785FFFF814900566F1B6569A06C");
		String upCode=null;
		String direction=PermissionConstant.UP_DIRECTION_UP_ROOT;
		findUnit(a, upCode, direction,"1");
		System.out.println("===========");
		return null;
	}
	/**
	 * 通过岗位ID查询组织权限
	 * 
	 * @param position
	 *            职位ID列表
	 * @param direction
	 *            方向（UA:所有上级节点、UR:上级跟节点、UI:上级非根节点、 OB:兄弟节点、OS:自己节点、
	 *            DA:下级所有节点、DL:下级所有叶子节点、DI:下级所有内部节点）
	 * @param offset
	 *            步长，从当前节点到第几层（上下）节点
	 * @return 组织列表，List中的对象是组织对象（com.cib.cap.org.vo.SCUnitProfileVO）
	 * @throws ServiceException
	 */
	public List findUnit(List position, String upCode, String direction,
			String offset) throws ServiceException {
				
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		if (null != upCode && upCode.length() > 0) {
			para.put("code", upCode);
		}
		if (PermissionConstant.UP_DIRECTION_OWNER.equalsIgnoreCase(direction)) {
			return find_iBatis("permission.findUnitOnly", para);
		} else if (PermissionConstant.UP_DIRECTION_UP_ALL
				.equalsIgnoreCase(direction)) {
			List codeList = find_iBatis("permission.findTreePathForUp", para);

			if (codeList == null || codeList.size() < 1) {
				return null;
			}

			String codeStrList = list2String(codeList);
			para.put("idList", codeStrList);
			return find_iBatis("permission.findUnitUp", para);
		} else if (PermissionConstant.UP_DIRECTION_DOWN_ALL
				.equalsIgnoreCase(direction)) {
			List tmp = new ArrayList();
			List list = find_iBatis("permission.findTreePath", para);
			List rv = new ArrayList();
			if(null==list||list.size()<1){
				return null;
			} 
			int count = list.size();			
			for(int i=0;i<count;i++){
				para.clear();
				para.put("path", "'"+list.get(i)+"%'");
				List ul = find_iBatis("permission.findUnitDownComm", para);
				if(ul==null){
					continue;
				}
				for(int j=0;j<ul.size();j++){
					SCUnitProfileVO vo = null;
					try{
						vo = (SCUnitProfileVO)ul.get(j);
						if(tmp.contains(vo.getLogicalKey())){
							continue;
						}
					}catch(Exception e){
						continue;
					}
					tmp.add(vo.getLogicalKey());
					rv.add(vo);
				}
			}
			
			return rv;
//			return find_iBatis("permission.findUnitDown", para);
		} else if (PermissionConstant.UP_DIRECTION_UP_ROOT
				.equalsIgnoreCase(direction)) {
			List codeList = find_iBatis("permission.findTreePathForUp", para);

			if (codeList == null || codeList.size() < 1) {
				return null;
			}
			List temp = new ArrayList();
			for(int i = 0; i< codeList.size(); i++){
				String treePath = (String)codeList.get(i);
				temp.add(treePath.substring(0,treePath.lastIndexOf(",")));
			}

			String codeStrList = list2String(temp);
			para.put("idList", codeStrList);
			return find_iBatis("permission.findUnitUp", para);
		}else if (PermissionConstant.UP_DIRECTION_OWNER_BROTHER
				.equalsIgnoreCase(direction)) {
			List codeList = find_iBatis("permission.findTreePathForUp", para);
			if (codeList == null || codeList.size() < 1) {
				return null;
			}
			List unitIdList=new ArrayList();
			List superUnitIdList=new ArrayList();
			for(int i = 0; i< codeList.size(); i++){
				String treePath = (String)codeList.get(i);
				if(treePath.indexOf(",")!=-1){
					String temp = treePath.substring(0,treePath.lastIndexOf(","));
					String unitId = treePath.substring(1+treePath.lastIndexOf(","));
					unitIdList.add(unitId);
					if(treePath.indexOf(",")==-1){
						superUnitIdList.add(temp);
					}else{
						superUnitIdList.add(temp.substring(1+temp.lastIndexOf(",")));
					}
				}
			}
			String unitIdListStr = list2String(unitIdList);
			String superUnitIdListStr = list2String(superUnitIdList);
			para.put("unitIdList", unitIdListStr);
			para.put("superUnitIdList", superUnitIdListStr);
			return find_iBatis("permission.findUnitBrother", para);
		}else if (PermissionConstant.UP_DIRECTION_DOWN_LEAF
				.equalsIgnoreCase(direction)) {
			List codeList = find_iBatis("permission.findTreePathForUp", para);
			if (codeList == null || codeList.size() < 1) {
				return null;
			}
			List unitIdLeafList=new ArrayList();
			String unitId = null;
			for(int i = 0; i< codeList.size(); i++){
				String treePath = (String)codeList.get(i);
				if(treePath.indexOf(",")==-1){
					unitId = treePath;
				}else{
					unitId = treePath.substring(1+treePath.lastIndexOf(","));
				}
				
				List unitIdList = findDownUnit(unitId);
				if(unitIdList==null||unitIdList.size()==0){
						unitIdLeafList.add(unitId);
				}else{
					findLeafUnit(unitIdList,unitIdLeafList);
				}
			}
			
			String codeStrList = list2String(unitIdLeafList);
			para.put("idList", codeStrList);
			return find_iBatis("permission.findUnitUp", para);
		}else if (PermissionConstant.UP_DIRECTION_DOWN_INSIDE
				.equalsIgnoreCase(direction)) {
			List codeList = find_iBatis("permission.findTreePathForUp", para);
			if (codeList == null || codeList.size() < 1) {
				return null;
			}
			List unitIdInsideList=new ArrayList();
			String unitId = null;
			for(int i = 0; i< codeList.size(); i++){
				String treePath = (String)codeList.get(i);
				if(treePath.indexOf(",")==-1){
					unitId = treePath;
				}else{
					unitId = treePath.substring(1+treePath.lastIndexOf(","));
				}
				
				List unitIdList = findDownUnit(unitId);
				if(unitIdList!=null&&unitIdList.size()>0){
					unitIdInsideList.add(unitId);
					findInsideUnit(unitIdList,unitIdInsideList);
				}
			}
			
			String codeStrList = list2String(unitIdInsideList);
			para.put("idList", codeStrList);
			return find_iBatis("permission.findUnitUp", para);
		}

		return null;
	}
	
	
	private void findLeafUnit(List unitIdList,List unitIdLeafList) throws ServiceException{
		for(int i = 0; i < unitIdList.size(); i++){
			String unitId = (String)unitIdList.get(i);
			List temp = findDownUnit(unitId);
			if(temp==null||temp.size()==0){
				unitIdLeafList.add(unitId);
			}else{
				findLeafUnit(temp,unitIdLeafList);
			}
		}
	}
	
	private void findInsideUnit(List unitIdList,List unitIdInsideList) throws ServiceException{
		for(int i = 0; i < unitIdList.size(); i++){
			String unitId = (String)unitIdList.get(i);
			List temp = findDownUnit(unitId);
			if(temp!=null&&temp.size()>0){
				unitIdInsideList.add(unitId);
				findInsideUnit(temp,unitIdInsideList);
			}
		}
	}
	
	private List findDownUnit(String unitId) throws ServiceException{
		Map para = new HashMap();
		para.put("unitId", unitId);
		return find_iBatis("permission.findDownUnit", para);
	}

	public List findUnitDataPermissionByUser(String user)
			throws ServiceException {
		List list = find_iBatis("permission.findPositionByStaffId", user);

		if (list == null || list.size() < 1) {
			list = new ArrayList();
		}

		list.add(CommonConstants.PUBLIC_PEMISSION_POSITION_ID);

		Map para = new HashMap();
		para.put("position", list2String(list, "'"));
		return find_iBatis("permission.findUnitDataPermission4List", para);
	}

	/**
	 * 列表转换成字符串
	 * 
	 * @param list
	 * @param space
	 * @return
	 */
	private static String list2String(List list, String space) {

		if (null == list || list.size() < 1) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		int count = list.size();

		if (null == space || space.length() < 1) {
			for (int i = 0; i < count; i++) {
				sb.append(list.get(i));
				sb.append(",");
			}
		} else {
			for (int i = 0; i < count; i++) {
				sb.append(space);
				sb.append(list.get(i));
				sb.append(space);
				sb.append(",");
			}
		}
		sb.deleteCharAt(sb.length() - 1);

		return sb.toString();
	}

	/**
	 * 列表转换成字符串
	 * 
	 * @param list
	 * @param space
	 * @return
	 */
	private static String list2String(List list) {

		if (null == list || list.size() < 1) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		int count = list.size();

		String space = "'";
		String tmp = null;
		for (int i = 0; i < count; i++) {
			tmp = (String) list.get(i);

			if (tmp == null || "null".equalsIgnoreCase(tmp) || tmp.trim().length() < 1) {
				continue;
			}
			
			String[] arr = tmp.split(",");			
			int arrCount = arr.length;
			for(int j=0;j<arrCount;j++){
				tmp = arr[j];
				if(tmp==null||tmp.length() < 1){
					continue;
				}
				sb.append(space);
				sb.append(tmp);
				sb.append(space);
				sb.append(",");
			}
		}
		if(sb.length()>0){
			sb.deleteCharAt(sb.length() - 1);
		}

		return sb.toString();
	}

	private static String array2String(String[] list, String space) {

		if (null == list || list.length < 1) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		int count = list.length;

		if (null == space || space.length() < 1) {
			for (int i = 0; i < count; i++) {
				sb.append(list[i]);
				sb.append(",");
			}
		} else {
			for (int i = 0; i < count; i++) {
				sb.append(space);
				sb.append(list[i]);
				sb.append(space);
				sb.append(",");
			}
		}
		sb.deleteCharAt(sb.length() - 1);

		return sb.toString();
	}

	public String findSelfDataPermissionStringListByUser(String user,
			String dpCode, String object) throws ServiceException {
		List list = find_iBatis("permission.findPositionByStaffId", user);

		if (list == null || list.size() < 1) {
			list = new ArrayList();
		}

		list.add(CommonConstants.PUBLIC_PEMISSION_POSITION_ID);

		List code = new ArrayList();
		code.add(dpCode);

		return findSelfDataPermissionStringList(list, code, object);
	}

	public String findUnitPathName(String path) throws ServiceException {
		String[] array = path.split(",");
		String paraStr = array2String(array, "'");
		Map para = new HashMap();
		para.put("path", paraStr);
		List list = this.find_iBatis("permission.findUnitPathName", para);

		if (null == list || list.size() < 1) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		int count = list.size();
		if (count < 1) {
			return "";
		}
		count = count - 1;

		for (int i = count; i > -1; i--) {
			try {
				SCUnitProfileVO vo = (SCUnitProfileVO) list.get(i);
				sb.append(vo.getUnitName());
			} catch (Exception e) {
				continue;
			}
			sb.append(">>");
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}

	public String findUnitPathNameById(String unitId) throws ServiceException {
		SCUnitProfileVO vo = (SCUnitProfileVO) this.findByID_Hibernate_Get(SCUnitProfileVO.class,
				unitId);

		if (vo == null) {
			return "";
		}

		String path = vo.getTreePath();
		if (null == path || "null".equalsIgnoreCase(path)) {
			path = "";
		}
		path += unitId + ",";

		return findUnitPathName(path);
	}

	/**
	 * 获取指定单位ID的下属单位，包括自己单位
	 * 
	 * @param unitId    单位ID
	 * @return List中的对象是组织对象（com.cib.cap.org.vo.SCUnitProfileVO）
	 * @throws ServiceException
	 */
	public List findUnitDownById(String unitId,boolean include) throws ServiceException {
		Map para = new HashMap();
		para.put("unit", unitId);
		if(include){
			List tmp = new ArrayList();
			List list = find_iBatis("permission.findUnitPathById", para);
			List rv = new ArrayList();
			if(null==list||list.size()<1){
				return null;
			} 
			int count = list.size();			
			for(int i=0;i<count;i++){
				para.clear();
				para.put("path", "'"+list.get(i)+"%'");
				List ul = find_iBatis("permission.findUnitDownComm", para);
				if(ul==null){
					continue;
				}
				for(int j=0;j<ul.size();j++){
					SCUnitProfileVO vo = null;
					try{
						vo = (SCUnitProfileVO)ul.get(j);
						if(tmp.contains(vo.getLogicalKey())){
							continue;
						}
					}catch(Exception e){
						continue;
					}
					tmp.add(vo.getLogicalKey());
					rv.add(vo);
				}
			}
			
			return rv;
		}else{
			List tmp = new ArrayList();
			List list = find_iBatis("permission.findUnitPathById", para);
			List rv = new ArrayList();
			if(null==list||list.size()<1){
				return null;
			} 
			int count = list.size();			
			for(int i=0;i<count;i++){
				para.clear();
				para.put("path", "'"+list.get(i)+",%'");
				List ul = find_iBatis("permission.findUnitDownComm", para);
				if(ul==null){
					continue;
				}
				for(int j=0;j<ul.size();j++){
					SCUnitProfileVO vo = null;
					try{
						vo = (SCUnitProfileVO)ul.get(j);
						if(tmp.contains(vo.getLogicalKey())){
							continue;
						}
					}catch(Exception e){
						continue;
					}
					tmp.add(vo.getLogicalKey());
					rv.add(vo);
				}
			}
			
			return rv;
		}
	}

	public List findAllUnitDataPermission() throws ServiceException {
		List list = this.findAll_Hibernate_Object(IPUnitPermissionVO.class);
		return list;
	}

	public List findSelfDataPermissionByUser(String staffId)
			throws ServiceException {
		List list = find_iBatis("permission.findPositionByStaffId", staffId);

		if (list == null || list.size() < 1) {
			list = new ArrayList();
		}


		list.add(CommonConstants.PUBLIC_PEMISSION_POSITION_ID);
		Map para = new HashMap();
		para.put("position", list2String(list, "'"));
		return find_iBatis("permission.findSelfDataPermission4List", para);
	}

	public List findSelfDataPermissionByRole(List role)
			throws ServiceException {
		
		if(null==role||role.size()<1){
			return null;
		}
		List position = findPositionByRole(role);
		
		if(position ==null || position.size()<1){
			return null;
		}
		
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		return find_iBatis("permission.findSelfDataPermission4List", para);
	}
	
	private List findPositionByRole(List role) throws ServiceException{
		Map para = new HashMap();
		para.put("role", list2String(role, "'"));		
		return find_iBatis("permission.findPoisitionListByRoleList", para);
	}

	public List findUnitDataPermissionByRole(List role) throws ServiceException {
		if(null==role||role.size()<1){
			return null;
		}
		List position = findPositionByRole(role);
		
		if(position ==null || position.size()<1){
			return null;
		}
		
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		return find_iBatis("permission.findUnitDataPermission4List", para);
	}

	public List findUnitByRole(List role, String upCode, String direction,
			String offset) throws ServiceException {
		List position = findPositionByRole(role);
		
		if(position ==null || position.size()<1){
			return null;
		}
		return findUnit(position, upCode, direction, offset);
	}

	public List findSelfDataPermissionByUser(String staffId,boolean isPage)
			throws ServiceException {
		List list = find_iBatis("permission.findPositionByStaffId", staffId);

		if (list == null || list.size() < 1) {
			list = new ArrayList();
		}

		list.add(CommonConstants.PUBLIC_PEMISSION_POSITION_ID);

		Map para = new HashMap();
		para.put("position", list2String(list, "'"));
		
		if(!isPage){
			para.put("field","m.FIELD_CODE");
		}else{
			para.put("field","m.PAGE_CODE");
		}
		
		return find_iBatis("permission.findMetadataField", para);
	}

	public List findSelfDataPermission(List position, boolean isPage)
			throws ServiceException {
		
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		
		if(!isPage){
			para.put("field","m.FIELD_CODE");
		}else{
			para.put("field","m.PAGE_CODE");
		}
		
		return find_iBatis("permission.findMetadataField", para);
	}

	public List findSelfDataPermissionByRole(List role, boolean isPage)
			throws ServiceException {
		if(null==role||role.size()<1){
			return null;
		}
		List position = findPositionByRole(role);
		
		if(position ==null || position.size()<1){
			return null;
		}
		
		Map para = new HashMap();
		para.put("position", list2String(position, "'"));
		
		if(!isPage){
			para.put("field","m.FIELD_CODE");
		}else{
			para.put("field","m.PAGE_CODE");
		}
		
		return find_iBatis("permission.findMetadataField", para);
	}
	
	public List getAuthOrg(String unitid) throws ServiceException{
		SessionUserHolder suser = (SessionUserHolder) getBean("sessionUserHolder");
		HashMap resultMap = new HashMap();
		
		List findResult = new ArrayList();
		List unitIdList = new ArrayList(); 
		boolean firstNode = false;
		
		List authOrgList = suser.getAuthOrgList();

		//如果unitid为空则表示为第一级组织
		if(authOrgList==null || authOrgList.size()==0) {
			authOrgList=new ArrayList();
		}
		for(int i=0;i<authOrgList.size();i++){
			   HashMap unitMap = (HashMap)authOrgList.get(i);
			   String id= (String)unitMap.get("id");
			   String tree= (String)unitMap.get("tree");
			   String direction= (String)unitMap.get("direction");
			   unitMap.get("name");
			   //去掉tree前后","
			   if(tree !=null && tree.trim().length()>0){
				   if(tree.startsWith(",")){
					   tree=tree.substring(1);
				   }
				   if(tree.endsWith(",")){
					   tree=tree.substring(0, tree.length()-1);
				   }
			   }
			   
			   if(unitid == null || unitid.trim().length()==0){
				   firstNode = true;
				   
				   //自己节点
				   if(PermissionConstant.UP_DIRECTION_OWNER.equalsIgnoreCase(direction)){
							  SCUnitProfileVO unitVo = unitService.getUnitByUnitId(id);
							  resultMap.put(id, unitVo);
					  log.debug(">>>>>>>>>>组织权限方向：自己节点<<<<<<<<<<");
					  continue;
				    }
				   
				   //上级根节点
				   if(PermissionConstant.UP_DIRECTION_UP_ROOT.equalsIgnoreCase(direction)){
						  if(tree ==null || tree.trim().length()==0){
							  
						  }else{
							  String[] treeArray=tree.split(",");
							  String _unitid=treeArray[0];
							  SCUnitProfileVO unitVo = unitService.getUnitByUnitId(_unitid);
							  resultMap.put(_unitid, unitVo);
						  }
						  log.debug(">>>>>>>>>>组织权限方向：上级根节点<<<<<<<<<<");
						  continue;
				    }
				   
				   //上级非根节点
				   if(PermissionConstant.UP_DIRECTION_UP_INSIDE.equalsIgnoreCase(direction)){
					  if(tree ==null || tree.trim().length()==0){
					  }else{
						  String[] treeArray=tree.split(",");
						  int iinside=treeArray.length;
						  if(iinside>1){
							  String _unitid=treeArray[1];
							  SCUnitProfileVO unitVo = unitService.getUnitByUnitId(_unitid);
							  resultMap.put(_unitid, unitVo);
						  }
					  }
					  log.debug(">>>>>>>>>>组织权限方向：上级非根节点<<<<<<<<<<");
					  continue;
				   }
				   
				   //上级所有节点
				   if(PermissionConstant.UP_DIRECTION_UP_ALL.equalsIgnoreCase(direction)){
					  if(tree ==null || tree.trim().length()==0){
						  
					  }else{
						  String[] treeArray=tree.split(",");
						  String _unitid=treeArray[0];
						  SCUnitProfileVO unitVo = unitService.getUnitByUnitId(_unitid);
						  resultMap.put(_unitid, unitVo);
					  }
					  log.debug(">>>>>>>>>>组织权限方向：所有上级节点<<<<<<<<<<");
					  continue;
				   }
				   
				   //兄弟节点
				   if(PermissionConstant.UP_DIRECTION_OWNER_BROTHER.equalsIgnoreCase(direction)){
					   
						Map para = new HashMap();
						if(tree ==null || tree.trim().length()==0){
							para.put("unitid",tree);
							List unitListByTreePath= find_iBatis("permission.getAllChildUnitByUnitId", "");
							
							for(int iunit=0;i<unitListByTreePath.size();i++){
								SCUnitProfileVO unitVo1 = (SCUnitProfileVO)unitListByTreePath.get(iunit);
								if(!id.equalsIgnoreCase(unitVo1.getLogicalKey())){
									resultMap.put(unitVo1.getLogicalKey(), unitVo1);
								}								
							}
						}else{							
							String[] treeArray= tree.split(",");
							int ibrother=treeArray.length;
							new ArrayList();
							if(ibrother>1){
								getBrother(id, tree,resultMap);  
							}
						}
						 log.debug(">>>>>>>>>>组织权限方向：兄弟节点<<<<<<<<<<");
						 continue;
							  
				    }
				   
				   //所有下级节点
				   if(PermissionConstant.UP_DIRECTION_DOWN_ALL.equalsIgnoreCase(direction)){
					   getDownAll(id, resultMap);
					   log.debug(">>>>>>>>>>组织权限方向：所有下级节点<<<<<<<<<<");
					   continue;
				   }
				   
				   //所有下级叶子节点
				   /**
				    * 说明：先找到下级节点。在根据下级节点的treepath找，如果结果等于1（自己），表明其为下级叶子节点
				    */
				   if(PermissionConstant.UP_DIRECTION_DOWN_LEAF.equalsIgnoreCase(direction)){
					   getDownLeaf(id, resultMap);
					   log.debug(">>>>>>>>>>组织权限方向：所有下级叶子节点<<<<<<<<<<");
					   continue;
				   }
				   
				   //下级所有内部节点
				   /**
				    * 说明：先找到下级节点。在根据下级节点的treepath找，如果结果大于1，表明其为内部节点
				    */
				   if(PermissionConstant.UP_DIRECTION_DOWN_INSIDE.equalsIgnoreCase(direction)){
					   getDownInside(id, resultMap);
					   log.debug(">>>>>>>>>>组织权限方向：所有下级叶子节点<<<<<<<<<<");
					   continue;
				   }
				   
			   }else{
				   
				   firstNode = false;
				   
				   new HashMap();
				   SCUnitProfileVO unitVo = unitService.getUnitByUnitId(unitid);
				   List unitvoListTest = unitService.getUnitsBySuperUnit(unitVo);
				   
                   if(unitvoListTest != null && unitvoListTest.size()>0){
                	   
                	   for(int itest=0;itest<unitvoListTest.size();itest++){
                		   SCUnitProfileVO unitTestVo =(SCUnitProfileVO)unitvoListTest.get(itest);
                		   if(unitTestVo ==null ){
                			   continue;
                		   }
                		   //TODO 替换成新的
                		   //isTheUnitHasPriv(resultMap, id, tree, direction, unitTestVo);
                		   isTheUnitHasPriv(findResult, unitIdList, id, tree, direction, unitTestVo);
                	   }
                   }
			   }
		}
		
		List NodDupList = findResult;
		if(firstNode){
			findResult = new ArrayList(resultMap.values());
	        NodDupList = getNodDupList(findResult);
		}		
        
        List result = NodDupList;
        if(unitid == null || unitid.trim().length()==0){
        	result = filterResult(NodDupList,authOrgList);
        }
		return result;
		
	}
	
	/**
	 * 最新的实现，修正排序
	 * @param resultList
	 * @param uinitIdList
	 * @param id
	 * @param tree
	 * @param direction
	 * @param unitTestVo
	 * @return
	 * @throws ServiceException
	 */
	private boolean isTheUnitHasPriv(List resultList,List uinitIdList, String id, String tree,
			String direction, SCUnitProfileVO unitTestVo) throws ServiceException {
		String unitTestId=unitTestVo.getLogicalKey();
		boolean flag = false;
	   unitTestVo.getUnitName();
	   //自己节点
	   if(PermissionConstant.UP_DIRECTION_OWNER.equalsIgnoreCase(direction)){
	          if(id.equalsIgnoreCase(unitTestId)){				  
				  if(!uinitIdList.contains(unitTestId)){
					  resultList.add(unitTestVo);
					  uinitIdList.add(unitTestId);
					  flag = true;
				  }				  
		          log.debug(">>>>>>>>>>组织权限方向：自己节点<<<<<<<<<<");
	          }
	    }
	   
	   //上级根节点
	   else if(PermissionConstant.UP_DIRECTION_UP_ROOT.equalsIgnoreCase(direction)){
			  if(tree ==null || tree.trim().length()==0){ 
			  }else{
				  String[] treeArray=tree.split(",");
				  String _unitid=treeArray[0];
				  if(_unitid.equalsIgnoreCase(unitTestId)){
					  if(!uinitIdList.contains(unitTestId)){
						  resultList.add(unitTestVo);
						  uinitIdList.add(unitTestId);
						  flag = true;
					  }		
				  } 
			  }
			  log.debug(">>>>>>>>>>组织权限方向：上级根节点<<<<<<<<<<");
	    }
	   
	   //上级非根节点
	   else if(PermissionConstant.UP_DIRECTION_UP_INSIDE.equalsIgnoreCase(direction)){
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null && !downTestTreepath.equalsIgnoreCase(unitTestVo.getLogicalKey())){
			   //tree必须以downTreepath开头
			   boolean b= tree.startsWith(downTestTreepath);
			   if(b){
				   if(downTestTreepath.length()<tree.length()){
					   if(!uinitIdList.contains(unitTestId)){
							  resultList.add(unitTestVo);
							  uinitIdList.add(unitTestId);
							  flag = true;
						  }		
				   }
			   }
		   }
		  log.debug(">>>>>>>>>>组织权限方向：上级非根节点<<<<<<<<<<");
	   }
	   
	   //上级所有节点
	   else if(PermissionConstant.UP_DIRECTION_UP_ALL.equalsIgnoreCase(direction)){
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null ){
			   //tree必须以downTreepath开头
			   boolean b= tree.startsWith(downTestTreepath);
			   if(b){
				   if(downTestTreepath.length()<tree.length()){
					   if(!uinitIdList.contains(unitTestId)){
							  resultList.add(unitTestVo);
							  uinitIdList.add(unitTestId);
							  flag = true;
						  }		
				   }
			   }
		   }
		  log.debug(">>>>>>>>>>组织权限方向：所有上级节点<<<<<<<<<<");
	   }
	   
	   //兄弟节点
	   else if(PermissionConstant.UP_DIRECTION_OWNER_BROTHER.equalsIgnoreCase(direction)){
		   					
			String[] treeArray= tree.split(",");
			int ibrother=treeArray.length;
			new ArrayList();
			
			StringBuffer treeNoLestBuffer = new StringBuffer();
			for(int itree=0;itree<ibrother-1;itree++){
				treeNoLestBuffer.append(treeArray[itree]);
				treeNoLestBuffer.append(",");
			}
			
			String treeNoLest = treeNoLestBuffer.toString();
			String resultTreePath = unitTestVo.getTreePath();
			
			String[] resultTreePathArray= resultTreePath.split(",");
			int iresultBrother=resultTreePathArray.length;
			
			StringBuffer resultTreeNoLestBuffer = new StringBuffer();
			for(int iresulttree=0;iresulttree<iresultBrother-1;iresulttree++){
				resultTreeNoLestBuffer.append(resultTreePathArray[iresulttree]);
				resultTreeNoLestBuffer.append(",");
			}
			String treeResultNoLest = resultTreeNoLestBuffer.toString();
			if(treeNoLest.equalsIgnoreCase(treeResultNoLest) && ibrother==iresultBrother){
				if(!id.equalsIgnoreCase(unitTestVo.getLogicalKey())){
					if(!uinitIdList.contains(unitTestId)){
						  resultList.add(unitTestVo);
						  uinitIdList.add(unitTestId);
						  flag = true;
					  }		
				}	
			}
		 log.debug(">>>>>>>>>>组织权限方向：兄弟节点<<<<<<<<<<");
			  
	  }
	   
	   //所有下级节点
	   else if(PermissionConstant.UP_DIRECTION_DOWN_ALL.equalsIgnoreCase(direction)){
		   
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null && !downTestTreepath.equalsIgnoreCase(unitTestVo.getLogicalKey())){
			   //tree必须以downTreepath开头
			   boolean b= downTestTreepath.startsWith(tree);
			   if(b){
				   if(downTestTreepath.length()>tree.length()){
					   if(!uinitIdList.contains(unitTestId)){
							  resultList.add(unitTestVo);
							  uinitIdList.add(unitTestId);
							  flag = true;
						  }		
				   }
			   }
		   }
		  log.debug(">>>>>>>>>>组织权限方向：上级非根节点<<<<<<<<<<");
	   }
	   
	   //所有下级叶子节点
	   /**
	    * 说明：先找到下级节点。在根据下级节点的treepath找，如果结果等于1（自己），表明其为下级叶子节点
	    */
	   else if(PermissionConstant.UP_DIRECTION_DOWN_LEAF.equalsIgnoreCase(direction)){
		   
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null && !downTestTreepath.equalsIgnoreCase(unitTestVo.getLogicalKey())){
			   //tree必须以downTreepath开头
			   boolean b= downTestTreepath.startsWith(tree);
			   if(b){
				   if(downTestTreepath.length()>tree.length()){
					   int count = unitService.getUnitCountBySuperUnit(unitTestVo);
					   if(count == 0 ){
						   if(!uinitIdList.contains(unitTestId)){
								  resultList.add(unitTestVo);
								  uinitIdList.add(unitTestId);
								  flag = true;
							  }		
					   }
				   }
			   }
		   }
	   }
	   
	   //下级所有内部节点
	   /**
	    * 说明：先找到下级节点。在根据下级节点的treepath找，如果结果大于1，表明其为内部节点
	    */
	   else if(PermissionConstant.UP_DIRECTION_DOWN_INSIDE.equalsIgnoreCase(direction)){
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null && !downTestTreepath.equalsIgnoreCase(unitTestVo.getLogicalKey())){
			   //tree必须以downTreepath开头
			   boolean b= downTestTreepath.startsWith(tree);
			   if(b){
				   if(downTestTreepath.length()>tree.length()){
					   int count = unitService.getUnitCountBySuperUnit(unitTestVo);
					   if(count>0 ){
						   if(!uinitIdList.contains(unitTestId)){
								  resultList.add(unitTestVo);
								  uinitIdList.add(unitTestId);
								  flag = true;
							  }		
					   }
				   }
			   }
		   }
	   }
		return flag;
	}

	/**
	 * @Deprecated 不推荐使用方法
	 * @param resultMap
	 * @param id
	 * @param tree
	 * @param direction
	 * @param unitTestVo
	 * @return
	 * @throws ServiceException
	 */
	@Deprecated
	private boolean isTheUnitHasPriv(HashMap resultMap, String id, String tree,
			String direction, SCUnitProfileVO unitTestVo) throws ServiceException {
		String unitTestId=unitTestVo.getLogicalKey();
		boolean flag = false;
	   unitTestVo.getUnitName();
	   //自己节点
	   if(PermissionConstant.UP_DIRECTION_OWNER.equalsIgnoreCase(direction)){
	          if(id.equalsIgnoreCase(unitTestId)){
				  resultMap.put(unitTestId, unitTestVo);
				  flag = true;
		          log.debug(">>>>>>>>>>组织权限方向：自己节点<<<<<<<<<<");
	          }
	    }
	   
	   //上级根节点
	   else if(PermissionConstant.UP_DIRECTION_UP_ROOT.equalsIgnoreCase(direction)){
			  if(tree ==null || tree.trim().length()==0){ 
			  }else{
				  String[] treeArray=tree.split(",");
				  String _unitid=treeArray[0];
				  if(_unitid.equalsIgnoreCase(unitTestId)){
					  resultMap.put(unitTestId, unitTestVo);
					  flag = true;
				  } 
			  }
			  log.debug(">>>>>>>>>>组织权限方向：上级根节点<<<<<<<<<<");
	    }
	   
	   //上级非根节点
	   else if(PermissionConstant.UP_DIRECTION_UP_INSIDE.equalsIgnoreCase(direction)){
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null && !downTestTreepath.equalsIgnoreCase(unitTestVo.getLogicalKey())){
			   //tree必须以downTreepath开头
			   boolean b= tree.startsWith(downTestTreepath);
			   if(b){
				   if(downTestTreepath.length()<tree.length()){
					   resultMap.put(unitTestId, unitTestVo);
					   flag = true;
				   }
			   }
		   }
		  log.debug(">>>>>>>>>>组织权限方向：上级非根节点<<<<<<<<<<");
	   }
	   
	   //上级所有节点
	   else if(PermissionConstant.UP_DIRECTION_UP_ALL.equalsIgnoreCase(direction)){
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null ){
			   //tree必须以downTreepath开头
			   boolean b= tree.startsWith(downTestTreepath);
			   if(b){
				   if(downTestTreepath.length()<tree.length()){
					   resultMap.put(unitTestId, unitTestVo);
					   flag = true;
				   }
			   }
		   }
		  log.debug(">>>>>>>>>>组织权限方向：所有上级节点<<<<<<<<<<");
	   }
	   
	   //兄弟节点
	   else if(PermissionConstant.UP_DIRECTION_OWNER_BROTHER.equalsIgnoreCase(direction)){
		   					
			String[] treeArray= tree.split(",");
			int ibrother=treeArray.length;
			new ArrayList();
			
			StringBuffer treeNoLestBuffer = new StringBuffer();
			for(int itree=0;itree<ibrother-1;itree++){
				treeNoLestBuffer.append(treeArray[itree]);
				treeNoLestBuffer.append(",");
			}
			
			String treeNoLest = treeNoLestBuffer.toString();
			String resultTreePath = unitTestVo.getTreePath();
			
			String[] resultTreePathArray= resultTreePath.split(",");
			int iresultBrother=resultTreePathArray.length;
			
			StringBuffer resultTreeNoLestBuffer = new StringBuffer();
			for(int iresulttree=0;iresulttree<iresultBrother-1;iresulttree++){
				resultTreeNoLestBuffer.append(resultTreePathArray[iresulttree]);
				resultTreeNoLestBuffer.append(",");
			}
			String treeResultNoLest = resultTreeNoLestBuffer.toString();
			if(treeNoLest.equalsIgnoreCase(treeResultNoLest) && ibrother==iresultBrother){
				if(!id.equalsIgnoreCase(unitTestVo.getLogicalKey())){
					resultMap.put(unitTestVo.getLogicalKey(), unitTestVo);
					 flag = true;
				}	
			}
		 log.debug(">>>>>>>>>>组织权限方向：兄弟节点<<<<<<<<<<");
			  
	  }
	   
	   //所有下级节点
	   else if(PermissionConstant.UP_DIRECTION_DOWN_ALL.equalsIgnoreCase(direction)){
		   
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null && !downTestTreepath.equalsIgnoreCase(unitTestVo.getLogicalKey())){
			   //tree必须以downTreepath开头
			   boolean b= downTestTreepath.startsWith(tree);
			   if(b){
				   if(downTestTreepath.length()>tree.length()){
					   resultMap.put(unitTestId, unitTestVo);
					   flag = true;
				   }
			   }
		   }
		  log.debug(">>>>>>>>>>组织权限方向：上级非根节点<<<<<<<<<<");
	   }
	   
	   //所有下级叶子节点
	   /**
	    * 说明：先找到下级节点。在根据下级节点的treepath找，如果结果等于1（自己），表明其为下级叶子节点
	    */
	   else if(PermissionConstant.UP_DIRECTION_DOWN_LEAF.equalsIgnoreCase(direction)){
		   
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null && !downTestTreepath.equalsIgnoreCase(unitTestVo.getLogicalKey())){
			   //tree必须以downTreepath开头
			   boolean b= downTestTreepath.startsWith(tree);
			   if(b){
				   if(downTestTreepath.length()>tree.length()){
					   int count = unitService.getUnitCountBySuperUnit(unitTestVo);
					   if(count == 0 ){
						   resultMap.put(unitTestVo.getLogicalKey(), unitTestVo);
						   flag = true;
					   }
				   }
			   }
		   }
	   }
	   
	   //下级所有内部节点
	   /**
	    * 说明：先找到下级节点。在根据下级节点的treepath找，如果结果大于1，表明其为内部节点
	    */
	   else if(PermissionConstant.UP_DIRECTION_DOWN_INSIDE.equalsIgnoreCase(direction)){
		   String downTestTreepath =unitTestVo.getTreePath();
		   if(downTestTreepath != null && !downTestTreepath.equalsIgnoreCase(unitTestVo.getLogicalKey())){
			   //tree必须以downTreepath开头
			   boolean b= downTestTreepath.startsWith(tree);
			   if(b){
				   if(downTestTreepath.length()>tree.length()){
					   int count = unitService.getUnitCountBySuperUnit(unitTestVo);
					   if(count>0 ){
						   resultMap.put(unitTestId, unitTestVo);
						   flag = true;
					   }
				   }
			   }
		   }
	   }
		return flag;
	}
	
  public String getNextString(String s1,String s,String type){
	  if(s==null || s1.trim().length()==0 || s.toString().trim().length()==0){
		  return "";
	  } 
	  String _s="";
	  if(PermissionConstant.UP_DIRECTION_UP_ALL.equalsIgnoreCase(type)){
		  int lasti=s.lastIndexOf(",");
		  if(lasti<0){ 
			  return ""; 
		  }
		  _s=s.substring(0, lasti);		  
	  }	 
	  
	  if(PermissionConstant.UP_DIRECTION_UP_INSIDE.equalsIgnoreCase(type)){
		  int lasti=s.indexOf(",");
		  if(lasti<0){ 
			  return ""; 
		  }
		  _s=s.substring(lasti+1, s.length());		  
	  }	
	  
	  StringBuffer s2=new StringBuffer(_s);
	  s2.append(",");
	  String result="";
	  
	  int i= s2.indexOf(s1);
	  if(i<0){
		  return ""; 
	  }
	  String  doAfterString= s2.substring(i+s1.length()+1, s2.length());
	  String[] resultArray=doAfterString.split(",");
	  result=resultArray[0];
	  if(result.equals(s1)){
		  return ""; 
	  }
	  return result;		  
  }
  
  public HashMap getBrother(String id ,String tree,HashMap resultMap) throws ServiceException{
		String[] treeArray= tree.split(",");
		int ibrother=treeArray.length;
		List unitListByTreePath=new ArrayList();
		Map para = new HashMap();
		
		StringBuffer treeNoLestBuffer = new StringBuffer();
		for(int itree=0;itree<ibrother-1;itree++){
			treeNoLestBuffer.append(treeArray[itree]);
			treeNoLestBuffer.append(",");
		}
		String seltree=treeNoLestBuffer.substring(0, treeNoLestBuffer.length()-1);
		para.put("unitid",seltree);
		unitListByTreePath= find_iBatis("permission.getAllChildUnitByUnitId", para);
		String treeNoLest = treeNoLestBuffer.toString();
		for(int iunit=0;iunit<unitListByTreePath.size();iunit++){
			
			SCUnitProfileVO unitVo3= (SCUnitProfileVO)unitListByTreePath.get(iunit);
			String resultTreePath = unitVo3.getTreePath();
			
			String[] resultTreePathArray= resultTreePath.split(",");
			int iresultBrother=resultTreePathArray.length;
			
			StringBuffer resultTreeNoLestBuffer = new StringBuffer();
			for(int iresulttree=0;iresulttree<iresultBrother-1;iresulttree++){
				resultTreeNoLestBuffer.append(resultTreePathArray[iresulttree]);
				resultTreeNoLestBuffer.append(",");
			}
			String treeResultNoLest = resultTreeNoLestBuffer.toString();
			if(treeNoLest.equalsIgnoreCase(treeResultNoLest) && ibrother==iresultBrother){
				if(!id.equalsIgnoreCase(unitVo3.getLogicalKey())){
					resultMap.put(unitVo3.getLogicalKey(), unitVo3);
				}	
			}
		
		}
		return resultMap;  
  }
  
  //得到所有下级节点
  public HashMap getDownAll(String id,HashMap resultMap) throws ServiceException{
	   SCUnitProfileVO unitVo = unitService.getUnitByUnitId(id);
	   List unitvoListTest = unitService.getUnitsBySuperUnit(unitVo);
	   for(int iunitvoList=0;iunitvoList<unitvoListTest.size();iunitvoList++){
		   SCUnitProfileVO unitVo4Test = (SCUnitProfileVO)unitvoListTest.get(iunitvoList);
		   resultMap.put(unitVo4Test.getLogicalKey(), unitVo4Test);
	   }
	return resultMap;
  }

  //所有下级叶子节点
  public HashMap getDownLeaf(String id,HashMap resultMap) throws ServiceException{
	   SCUnitProfileVO unitVo = unitService.getUnitByUnitId(id);
	   List unitvoList =unitService.getUnitsBySuperUnit(unitVo);
	   for(int iunitvoList=0;iunitvoList<unitvoList.size();iunitvoList++){
		   SCUnitProfileVO unitVoDownLeaf = (SCUnitProfileVO)unitvoList.get(iunitvoList);
		   Map para = new HashMap();
		   String downtree=unitVoDownLeaf.getTreePath();
		   para.put("unitid",downtree);
		   List unitListByTreePath= find_iBatis("permission.getAllChildUnitByUnitId", para);
		   if(unitListByTreePath.size()==1){
			   resultMap.put(unitVoDownLeaf.getLogicalKey(), unitVoDownLeaf);
		   }
	   }
	return resultMap;
 }
  
  //下级所有内部节点
  public HashMap getDownInside(String id,HashMap resultMap) throws ServiceException{
	  SCUnitProfileVO unitVo = unitService.getUnitByUnitId(id);
	   List unitvoList =  unitService.getUnitsBySuperUnit(unitVo);
	   for(int iunitvoList=0;iunitvoList<unitvoList.size();iunitvoList++){
		   SCUnitProfileVO unitVoDownInside = (SCUnitProfileVO)unitvoList.get(iunitvoList);
		   Map para = new HashMap();
		   String downtree=unitVoDownInside.getTreePath();
		   para.put("unitid",downtree);
		   List unitListByTreePath= find_iBatis("permission.getAllChildUnitByUnitId", para);
		   if(unitListByTreePath.size()>1){
			   resultMap.put(unitVoDownInside.getLogicalKey(), unitVoDownInside);
		   }
	   }
	return resultMap;
 }
}
